package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"io"
	"log"
	"net/http"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil) // 将HTTP连接转换为WebSocket连接
	if err != nil {
		log.Println("upgrade error:", err)
		return
	}

	for {
		messageType, message, err := conn.ReadMessage() // 读取客户端发送的消息
		if err != nil {
			log.Println("read error:", err)
			break
		}

		// 处理收到的消息并进行相应操作
		fmt.Printf("Received message from client: %s\n", string(message))

		if string(message) == "read" {
			resp, err := http.Post("http://localhost:18889/api/readCard", "application/json", nil)
			bytes, err := io.ReadAll(resp.Body)
			err = conn.WriteMessage(messageType, bytes) // 向客户端发送消息
			if err != nil {
				log.Println("write error:", err)
				break
			}

			resp.Body.Close()
		}
	}
}

func main() {
	http.HandleFunc("/api/readCard", handleWebSocket) // 设置路由处理函数

	err := http.ListenAndServe("localhost:8080", nil) // 在本地主机上运行WebSocket服务器
	if err != nil {
		log.Fatal("listen and serve error: ", err)
	}
}
